package domain

import (
	"go-weixin/app/usercenter/model"
	"go-weixin/app/usercenter/rpc/internal/dao"
	"go-weixin/app/usercenter/rpc/internal/repo"
	"go-weixin/common/chendb"

	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/x/errors"
)

type PowerDomain struct {
	powerRepo repo.PowerRepo
	tableRepo repo.TableRepo
}

func NewPowerDomain(engine chendb.ChenDb) *PowerDomain {
	return &PowerDomain{
		powerRepo: dao.NewPowerDao(engine),
		tableRepo: dao.NewTableDao(engine),
	}
}

func (p PowerDomain) PowerAdd(name string, method int64, url string, parentId int64) error {
	power := new(model.PowerModel)
	power.Name = name
	power.Method = method
	power.Url = url
	power.ParentId = parentId
	affected, err := p.powerRepo.PowerAdd(power)
	if err != nil {
		logx.Error(err)
		return err
	}
	if affected == 0 {
		return errors.New(400, "权限添加失败")
	}
	return nil
}

func (p PowerDomain) PowerUpdate(id int64, method int64, name string, parentId int64, url string) error {
	power := &model.PowerModel{
		Method:   method,
		Name:     name,
		ParentId: parentId,
		Url:      url,
	}
	affected, err := p.powerRepo.PowerUpdate(id, power)
	if err != nil {
		logx.Errorf("power-update-err: %v", err)
		return err
	}

	if affected == 0 {
		logx.Error("power-update-err:affected=0")
		return errors.New(400, "power-update-err:affected=0")
	}
	return nil
}

func (p PowerDomain) PowerAddExist(name string, url string) error {
	has, err := p.tableRepo.TableExistByUrl(url)
	if err != nil {
		return err
	}
	if !has {
		return errors.New(400, "此url不存在与table中")
	}
	has, err = p.powerRepo.PowerExistByName(name)
	if err != nil {
		return err
	}
	if has {
		return errors.New(400, "权限名已经被注册")
	}
	return nil
}

func (p PowerDomain) PowerUpdateExist(name string, id int64) error {
	has, err := p.powerRepo.PowerUpdateExisByName(name, id)
	if err != nil {
		logx.Info(err)
		return err
	}
	if has {
		return errors.New(400, "权限名已经存在")
	}
	return nil
}

func (p PowerDomain) PowerList(page int64) ([]model.PowerModel, error) {
	limit := 10
	offset := 10 * (page - 1)
	powerList := make([]model.PowerModel, 0)
	err := p.powerRepo.PowerList(int64(limit), offset, &powerList)
	if err != nil {
		return nil, err
	}

	return powerList, nil
}

func (p PowerDomain) PowerDetail(id int64) (*model.PowerModel, error) {
	power := new(model.PowerModel)
	has, err := p.powerRepo.GetPowerById(id, power)
	if err != nil {
		return nil, err
	}

	if !has {
		return nil, errors.New(400, "查询权限失败")
	}
	return power, nil
}

func (p PowerDomain) PowerGetRole(id int64) ([]model.RoleModel, error) {
	powerList := make([]model.RoleModel, 0)
	err := p.powerRepo.PowerGetRoleById(id, &powerList)
	if err != nil {
		return nil, err
	}
	return powerList, nil
}

func (p PowerDomain) PowerGetUser(id int64) ([]model.UserModel, error) {
	userList := make([]model.UserModel, 0)
	err := p.powerRepo.PowerGetUserById(id, &userList)
	if err != nil {
		return nil, err
	}
	return userList, nil
}
